<?php

namespace Fox;

class Validate {

	private static $types = [
		'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
		'phone' => '/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/',
		'mobile' => '/^((\(\d{2,3}\))|(\d{3}\-))?1\d{10}$/',
		'url' => '/^https?:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\'=>+!]*([^<>\"\"])*$/',
		'id' => '/^\d{15}(\d{2}[A-Za-z0-9])?$/',
		'currency' => '/^\d+(\.\d+)?$/',
		'number' => '/^\d+$/',
		'qq' => '/^[1-9]\d{4,9}$/',
		'int' => '/^[-\+]?\d+$/',
		'double' => '/^[-\+]?\d+(\.\d+)?$/',
		'en' => '/^[A-Za-z]+$/',
		'ch' => '/^[\x{4e00}-\x{9fa5}]+$/u',
		'name' => '/^[a-z]\w{5,}$/i',
		'ip' => '/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/',
		'date' => '/^[1-9]\d{3}[-\/\\\]\d{1,2}[-\/\\\]\d{1,2}$/',
		'datetime' => '/^[1-9]\d{3}[-\/\\\]\d{1,2}[-\/\\\]\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}$/',
		'w' => '/^\w+$/',
		'z' => '/^[a-zA-Z0-9_\-\x{4e00}-\x{9fa5}]+$/u',
		'require' => '/^.+$/',
	];

	/**
	 * 数据验证函数
	 * @param $type 如果type参数以.（点）开头，该参数可以为空
	 * @param $val
	 * @return int
	 */
	public static function is($type, $val) {

		$dot = substr($type, 0, 1) == '.';
		if ($dot) {
			if (empty($val)) {
				return true;
			}
			$type = substr($type, 1);
		}
		$test = self::$types[$type];

		return is_string($test) ? preg_match($test, $val) : $test($val);
	}

	/**
	 * 扩展验证规则
	 * @param $type 扩展类型名字
	 * @param $reg_or_fun
	 * @internal param 可以为一个正则表达式 $fun ，或者函数
	 */
	public static function extend($type, $reg_or_fun) {
		self::$types[$type] = $reg_or_fun;
	}

}